class PIDController:
    def __init__(self, Kp=0.0, Ki=0.0, Kd=0.0, set_point=10.0):
        self.Kp = Kp  # 比例增益
        self.Ki = Ki  # 积分增益
        self.Kd = Kd  # 微分增益

        self.set_point = set_point  # 设定点
        self.previous_error = 0.0  # 上一次误差
        self.integral = 0.0  # 积分项

    def update(self, measured_value, dt):
        # 计算误差
        error = self.set_point - measured_value

        # 比例部分
        p_out = self.Kp * error

        # 积分部分
        self.integral += error * dt
        i_out = self.Ki * self.integral

        # 微分部分
        derivative = (error - self.previous_error) / dt
        d_out = self.Kd * derivative

        # 更新上一次误差
        self.previous_error = error

        # 返回总的输出
        print(f"error:{error:.4f} p_out: {p_out:.4f}, i_out: {i_out:.4f}, d_out: {d_out:.4f}")
        return p_out + i_out + d_out


# 示例使用：创建不同类型的控制器并更新它们的状态。
if __name__ == "__main__":
    import time

    # 假设我们有一个设定点为10的过程变量
    set_point = 10.0

    # 创建不同的控制器实例
    # pid_controller = PIDController(Kp=5.0)
    # pid_controller = PIDController(Kp=5.0, Ki=8.0)
    pid_controller = PIDController(Kp=5.0, Kd=0.6)
    # pid_controller = PIDController(Kp=5.0, Ki=0.8, Kd=0.1)
    count = 0

    # 模拟过程值的变化
    process_value = 0.0
    start_time = time.time()

    while abs(process_value - set_point) > 0.001:
        time.sleep(0.1)  # 模拟时间延迟
        current_time = time.time()
        dt = current_time - start_time
        start_time = current_time

        control_signal = pid_controller.update(process_value, dt)
        print(f"当前值: {process_value:.4f}, 控制信号: {(control_signal*dt):.4f}, 目标值: {set_point}")
        # 模拟应用控制信号后过程值的变化
        process_value += control_signal * dt  # 简化的例子
        count += 1
    
    print(f"end 当前值: {process_value}, 控制信号: {control_signal:.3f}, 目标值: {set_point}, count={count}")
""" 
Ki= 0.7, 97
Ki= 0.3, 214
Ki= 0.5, 134

"""